function ListNode(val, next) {
  this.val = (val===undefined ? 0 : val)
  this.next = (next===undefined ? null : next)
}
function createList(arr) {
  if(arr.length == 0)
    return null;
  let head = new ListNode(arr[0], null), headNode = head;
  for(let i = 1; i < arr.length; i++) {
    let temp = new ListNode(arr[i], null);
    head.next = temp;
    head = temp;
  }
  return headNode;
}
function showList(head) {
  while(head) {
    console.log(head.val);
    head = head.next;
  }
}

/**
 * @param {ListNode} head
 * @return {ListNode}
 */

var sortList = function(head) {
  head = createList(head);
  if(!head || !head.next) return head;
  let result = [], temp = head;
  while(temp) {
    result.push(temp.val);
    temp = temp.next;
  }
  result.sort((a, b) => a - b);
  let newHead = new ListNode(result[0], null);
  temp = newHead;
  for(let i = 1; i < result.length; i++) {
    let node = new ListNode(result[i], null);
    temp.next = node;
    temp = temp.next;
  }
  return newHead;
};
let head = [4, 2, 1, 3];
console.log(sortList(head));
head = [1,2,3,4,5];
console.log(sortList(head));

